
//127.0.0.1  本地环回 表示的就是当前主机 用来进行本地通信

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <iostream>
#include <memory>
#include <cstdlib>
#include <cstring>

#include <stdio.h>

#include <pthread.h>

#include "err.hpp"
#include "udp_client.hpp"
using namespace std;

static void Usage(string proc)
{
    cout << "Usage:\n\t" << proc << "port\n"
         << endl;
}


void *recever(void * args)
{
    int sock=*(static_cast<int*>(args));
    while(true)
    {
        // 收
        char buffer[1024];
        struct sockaddr_in temp; //可能来自不同服务器的报文，最好还是把这个保留
        socklen_t len=sizeof(temp);
       int n= recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&temp,&len);
        if(n > 0) 
        {
            buffer[n]='\0';
        // cout<<"sever echo>>>"<<buffer<<endl;
        }
    }
}
//./client severip severport
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        exit(USAGE_ERR);
        Usage(argv[0]);
    }

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "ctreate error" << strerror(errno) << std::endl;
        exit(CREATE_ERR);
    }
    string severip = argv[1];
    uint16_t severport = atoi(argv[2]);
    struct sockaddr_in sever;
    memset(&sever, 0, sizeof(sever));
    sever.sin_port = htons(severport);
    sever.sin_addr.s_addr = inet_addr(severip.c_str());
        // client肯定要bind 但是不需要自己bind OS帮忙

        //多线程化
        pthread_t tid;
        pthread_create(&tid,0,recever,&sock); //让一个线程不断收消息
        while(true)
        {
        // 用户输入
        cout << "Please Enter>>>";
        string message;
        getline(cin,message);
        //首次调用系统调用 发送数据的时候 OS在底层随机选择一个clienip+clientport bind&&构建发送的数据报文

        //发
        sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&sever, sizeof(sever));
        }

    
    return 0;
}